package com.vshop.service.task;

import com.vshop.config.datasource.DataSource;
import com.vshop.entity.agatewaytobeijing.JsonConstant;
import com.vshop.entity.agatewaytobeijing.Page;
import com.vshop.entity.agatewaytobeijing.syncpackage.response.OriginalPackage;
import com.vshop.entity.agatewaytobeijing.syncpartner.response.OriginalPartner;
import com.vshop.entity.alast.common.MerchantServicePlanOrderRecord;
import com.vshop.entity.alast.common.PartnerServicePlan;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.alast.linksentity.LinksOrdersPayment;
import com.vshop.entity.comentity.DevicePackagesRelation;
import com.vshop.entity.comentity.PartnerInfo;
import com.vshop.entity.comentity.PartnerPackage;
import com.vshop.mapper.task.ServicePlanTaskMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lm
 * @date 2020/9/24 9:29
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class ServicePlanTaskServiceImpl {
    @Resource
    private ServicePlanTaskMapper taskMapper;

    /**
     * 查询有没有需要去做查询确认订单状态的订单列表
     *
     * @return
     */
    public List<ServicePlanOrderRecord> queryServicePlanStatus() {

        return taskMapper.queryServicePlanStatus();
    }

    /**
     * 更新orderId的状态，订购时间，激活时间，预计结束时间
     *
     * @param record
     * @return
     */
    public Integer updateOrderIdStatus(ServicePlanOrderRecord record) {

        return taskMapper.updateOrderIdStatus(record);
    }

    /**
     * 查询需要去做开通订单操作的订单列表
     *
     * @return
     */
    public List<ServicePlanOrderRecord> queryServicePlanIsOpen() {

        return taskMapper.queryServicePlanIsOpen();
    }

    /**
     * 卡片是OTA卡片，以后再也不要发起开通了，这边把订单的isOpen状态改成1,以后不再参与轮循了
     *
     * @param record
     * @return
     */
    public Integer updateOtaFlagIsOpen(ServicePlanOrderRecord record) {

        return taskMapper.updateOtaFlagIsOpen(record);
    }

    /**
     * 每个月的15号去执行将包含上个月和之前的数据（service_plan_order_record_t）转移到（service_plan_order_record_hist_t）的操作
     *
     * @return
     */
    public Integer oldDataTransfer() {

        return taskMapper.oldDataTransfer();
    }

    /**
     * 转移执行完成之后将service_plan_order_record_t表中包含上个月和之前的空单删掉
     *
     * @return
     */
    public Integer oldEmptyDataDelete() {

        return taskMapper.oldEmptyDataDelete();
    }

    /**
     * 查询links的user_order_payment_manager_t表
     *
     * @return
     */
    @DataSource(name = "third")
    public List<LinksOrdersPayment> queryOrderPaymentList() {

        return taskMapper.queryOrderPaymentList();

    }

    /**
     * 将links的user_order_payment_manager_t表中的数据写入到v-shop的service_plan_order_record_t表
     *
     * @param or
     * @return
     */
    public Integer syncData(ServicePlanOrderRecord or) {

        return taskMapper.syncData(or);
    }

    /**
     * 回去告诉links的user_order_payment_manager_t表我收到记录了
     *
     * @param linksOrders
     * @return
     */
    @DataSource(name = "third")
    public Integer updateLinksIsSync(LinksOrdersPayment linksOrders) {

        return taskMapper.updateLinksIsSync(linksOrders);
    }


    /**
     * 根据渠道编码和套餐编码查询上架的套餐名称和套餐编码
     *
     * @param partnerCode
     * @param packageCode
     * @return
     */
    public List<PartnerServicePlan> queryServicePlan(String partnerCode, String packageCode) {
        return taskMapper.queryServicePlanShow(partnerCode, packageCode);
    }

    /**
     * 根据响应的page里面的参数totalCount计算出需要去执行请求的次数
     *
     * @param page
     * @return
     */
    public double countExecutionTimes(Page page) {
        //总条数
        Integer totalCount = page.getTotal_count();
        //预计要执行的次数
        double total;

        //这边以每次最大承受的1000为标准，看看需要执行多少次
        if (Math.ceil(totalCount / JsonConstant.CODE_1000) < 1) {
            total = 1;
        } else {
            total = Math.ceil(totalCount / JsonConstant.CODE_1000) + 1;
        }
        return total;

    }

    /**
     * 根据响应的page里面的参数totalCount计算出需要去执行请求的次数
     *
     * @param page
     * @return
     */
    public double countExecution(Page page) {
        //总条数
        Integer totalCount = page.getTotal_count();
        //预计要执行的次数
        double total;

        //这边以每次最大承受的1000为标准，看看需要执行多少次
        if (Math.ceil(totalCount / JsonConstant.CODE_500) < 1) {
            total = 1;
        } else {
            total = Math.ceil(totalCount / JsonConstant.CODE_500) + 1;
        }
        return total;

    }

    /**
     * 查询数据库里面是否已经有这个企业的数据
     *
     * @param partnerCode
     * @return
     */
    public Integer findPartnerExistOrNot(String partnerCode) {

        return taskMapper.findPartnerExistOrNot(partnerCode);
    }

    /**
     * 入库企业信息 ：partner_info_t
     *
     * @param partnerIndex
     * @param token
     * @param partners
     * @return
     */
    public Integer insertPartner(Integer partnerIndex, String token, OriginalPartner partners) {

        PartnerInfo partner = new PartnerInfo();
        partner.setPartnerIndex(String.valueOf(partnerIndex));
        partner.setPartnerName(partners.getPartner_name());
        partner.setPartnerCode(partners.getPartner_code());
        partner.setSecret(partners.getSecret());
        partner.setToken(token);
        partner.setPartnerGrade(partners.getPartner_type());
        partner.setPartnerHeader(partners.getConnector());
        partner.setPartnerPhone(partners.getPhone_num());
        partner.setPartnerEmail(partners.getEmail());
        partner.setCompanylogo("https://wx.linksfield.net/upload/logo/logo.png");
        return taskMapper.insertPartner(partner);

    }

    /**
     * 有partnerCode就根据partnerCode取企业信息查询，没有partnerCode就拿全部企业信息
     *
     * @param partnerCode
     * @return
     */
    public List<PartnerInfo> findPartnerCode(String partnerCode) {

        return taskMapper.findPartnerCode(partnerCode);
    }

    /**
     * 用partnerCode去数据表查看看有没有存在这个记录，有的话就不需要去请求同步的企业
     *
     * @param partnerCode
     * @return
     */
    public Integer queryOrNotPartnerCode(String partnerCode) {

        return taskMapper.queryOrNotPartnerCode(partnerCode);
    }

    /**
     * 根据partnerCode和packageCode查询套餐数据表有没有这条记录
     *
     * @param partnerCode
     * @param packageCode
     * @return
     */
    public Integer findPackageByCondition(String partnerCode, String packageCode) {
        return taskMapper.findPackageByCondition(partnerCode, packageCode);
    }

    /**
     * 根据mcc匹配对应的大洲中文名称
     *
     * @param mcc
     * @return
     */
    public String queryContinent(String mcc) {

        return taskMapper.queryContinent(mcc);
    }

    /**
     * 根据mcc匹配对应的大洲英文名称
     *
     * @param mcc
     * @return
     */
    public String queryContinentEN(String mcc) {

        return taskMapper.queryContinentEN(mcc);
    }

    /**
     * 根据mcc匹配对应的国家英文名称
     *
     * @param mcc
     * @return
     */
    public String queryCountryEN(String mcc) {

        return taskMapper.queryCountryEN(mcc);
    }

    /**
     * 入库原始套餐数据
     *
     * @param partnerCode
     * @param partnerName
     * @param originalPackage
     * @param continentName
     * @param continentNameEN
     * @param coverCountryEN
     * @return
     */
    public Integer storagePartnerPackage(String partnerCode, String partnerName, OriginalPackage originalPackage, String continentName, String continentNameEN, String coverCountryEN) {

        PartnerPackage product = new PartnerPackage();
        product.setPartnerCode(partnerCode);
        product.setPartnerName(partnerName);
        product.setPackageCode(originalPackage.getPackage_code());
        product.setPackageName(originalPackage.getPackage_name());
        product.setPackageNameEN(originalPackage.getPackage_name_en());
        product.setPackageShortDesc(originalPackage.getPackage_desc());
        product.setPackageFlow(originalPackage.getFlow());
        product.setPackageType(originalPackage.getPackage_type());
        product.setBuyType(originalPackage.getBuy_type());
        product.setPriceType(originalPackage.getPrice_type());
        product.setServiceCycleCount(originalPackage.getServiceCycleCount());
        product.setMinOrderPeriod(originalPackage.getMin_order_period());
        product.setMaxOrderPeriod(originalPackage.getMax_order_period());
        product.setPackageStatus(originalPackage.getStatus());
        if ("1".equals(originalPackage.getStatus())) {
            product.setStatus("0");
        } else if ("2".equals(originalPackage.getStatus()) || "3".equals(originalPackage.getStatus())) {
            product.setStatus("4");
        }
        product.setCoverMcc(originalPackage.getCover_country_mcc());
        product.setCoverCountrys(originalPackage.getCover_countrys());
        product.setCoverCountrysEN(coverCountryEN);
        product.setContinentName(continentName);
        product.setContinentNameEN(continentNameEN);
        product.setCostPrice(originalPackage.getWhole_price());
        product.setPackage_usage_attribute(originalPackage.getPackage_usage_attribute());

        return taskMapper.storagePartnerPackage(product);
    }

    /**
     * 用partnerCode和packageCode查询原始套餐的状态
     *
     * @param partnerCode
     * @param packageCode
     * @return
     */
    public String queryPackageStatusByCode(String partnerCode, String packageCode) {
        return taskMapper.queryPackageStatusByCode(partnerCode, packageCode);
    }

    /**
     * 更新partnerCode和packageCode原始套餐的状态
     *
     * @param partnerCode
     * @param packageCode
     * @param packageStatus
     * @param status
     */
    public Integer updatePackageStatus(String partnerCode, String packageCode, String packageStatus, String status) {
        PartnerPackage product = new PartnerPackage();
        product.setPartnerCode(partnerCode);
        product.setPackageCode(packageCode);
        product.setPackageStatus(packageStatus);
        product.setStatus(status);
        return taskMapper.updatePackageStatus(product);
    }

    /**
     * 更新partnerCode和packageCode新建套餐的状态
     *
     * @param partnerCode
     * @param packageCode
     * @param servicePlanStatus
     */
    public Integer updateServicePlanStatus(String partnerCode, String packageCode, String servicePlanStatus) {
        PartnerServicePlan servicePlan = new PartnerServicePlan();
        servicePlan.setPartnerCode(partnerCode);
        servicePlan.setPackageCode(packageCode);
        servicePlan.setServicePlanStatus(servicePlanStatus);
        return taskMapper.updateServicePlanStatus(servicePlan);
    }

    /**
     * 根据partnerCode和packageCode去原始套餐表匹配套餐的原始套餐中文名称
     *
     * @param partnerCode
     * @param packageCode
     * @return
     */
    public String queryPackageNameByCode(String partnerCode, String packageCode) {
        return taskMapper.queryPackageNameByCode(partnerCode, packageCode);
    }

    /**
     * 查询对应数据库："partner_device_packages_relation_t_" + partnerIndex有没有某条数据
     *
     * @param tableName
     * @param partnerCode
     * @param packageCode
     * @param deviceCode
     * @return
     */
    public Integer findCountByCondition(String tableName, String partnerCode, String packageCode, String deviceCode) {
        return taskMapper.findCountByCondition(tableName, partnerCode, packageCode, deviceCode);
    }

    /**
     * 入库数据："partner_device_packages_relation_t_" + partnerIndex
     *
     * @param tableName
     * @param partnerCode
     * @param partnerName
     * @param packageCode
     * @param packageName
     * @param deviceCode
     * @return
     */
    public Integer storageRelation(String tableName, String partnerCode, String partnerName, String packageCode, String packageName, String deviceCode) {
        DevicePackagesRelation relation = new DevicePackagesRelation();
        relation.setPartnerCode(partnerCode);
        relation.setPartnerName(partnerName);
        relation.setPackageCode(packageCode);
        relation.setPackageName(packageName);
        relation.setDeviceCode(deviceCode);
        return taskMapper.storageRelation(tableName, relation);
    }

    /**
     * 原始数据表更新数据表里面的serviceCycleCount字段的值
     * <p>
     * partner_package_t
     *
     * @param partnerCode
     * @param packageCode
     * @param originalPackage
     * @return
     */
    public Integer updatePartnerPackageCycleCount(String partnerCode, String packageCode, OriginalPackage originalPackage) {
        PartnerPackage product = new PartnerPackage();
        product.setPartnerCode(partnerCode);
        product.setPackageCode(packageCode);
        product.setServiceCycleCount(originalPackage.getServiceCycleCount());
        return taskMapper.updatePartnerPackageCycleCount(product);
    }

    /**
     * @return
     */
    public List<ServicePlanOrderRecord> queryServicePlanOrderRecordList() {
        return taskMapper.queryServicePlanOrderRecordList();
    }

    /**
     * @param deviceCode
     * @return
     */
    @DataSource(name = "second")
    public String queryDeviceSort(String deviceCode) {
        return taskMapper.queryDeviceSort(deviceCode);
    }

    /**
     * @param or
     */
    @DataSource(name = "second")
    public Integer syncOrderData(MerchantServicePlanOrderRecord or) {
        return taskMapper.syncOrderData(or);
    }
}
